package com.atguigu.xuexiplus.service.impl;

import com.atguigu.xuexiplus.dto.SubmitAnswerDTO;
import com.atguigu.xuexiplus.dto.SubmissionDetailsVO;
import com.atguigu.xuexiplus.entity.Question;
import com.atguigu.xuexiplus.entity.QuizSubmission;
import com.atguigu.xuexiplus.entity.UserAnswer;
import com.atguigu.xuexiplus.mapper.QuestionMapper;
import com.atguigu.xuexiplus.mapper.QuizSubmissionMapper;
import com.atguigu.xuexiplus.mapper.UserAnswerMapper;
import com.atguigu.xuexiplus.service.QuizService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QuizServiceImpl implements QuizService {

    private final QuestionMapper questionMapper;
    private final QuizSubmissionMapper quizSubmissionMapper;
    private final UserAnswerMapper userAnswerMapper;

    public QuizServiceImpl(QuestionMapper questionMapper,
                           QuizSubmissionMapper quizSubmissionMapper,
                           UserAnswerMapper userAnswerMapper) {
        this.questionMapper = questionMapper;
        this.quizSubmissionMapper = quizSubmissionMapper;
        this.userAnswerMapper = userAnswerMapper;
    }

    @Override
    @Transactional
    public Map<String, Object> submit(SubmitAnswerDTO dto) {
        int total = dto.getAnswers() == null ? 0 : dto.getAnswers().size();
        int correct = 0;

        Map<Long, Question> questionMap = new HashMap<>();

        // Create submission summary first
        QuizSubmission submission = new QuizSubmission();
        submission.setUserId(dto.getUserId());
        submission.setSubject(dto.getSubject());
        submission.setTotalQuestions(total);
        submission.setCorrectCount(0);
        submission.setScore(0.0);
        quizSubmissionMapper.insert(submission);

        // Evaluate answers using DB-correct answers
        for (SubmitAnswerDTO.Item item : dto.getAnswers()) {
            Question q = questionMapper.findById(item.getQuestionId());
            String correctAnswer = q == null ? "" : q.getCorrectAnswer();
            boolean isCorrect = correctAnswer != null && correctAnswer.equalsIgnoreCase(item.getUserAnswer());
            if (isCorrect) correct++;

            UserAnswer ua = new UserAnswer();
            ua.setSubmissionId(submission.getId());
            ua.setQuestionId(item.getQuestionId());
            ua.setUserAnswer(item.getUserAnswer());
            ua.setCorrectAnswer(correctAnswer);
            ua.setIsCorrect(isCorrect ? 1 : 0);
            userAnswerMapper.insert(ua);
        }

        double score = total == 0 ? 0.0 : (correct * 100.0 / total);
        submission.setCorrectCount(correct);
        submission.setScore(score);
        quizSubmissionMapper.updateScore(submission);

        Map<String, Object> result = new HashMap<>();
        result.put("submissionId", submission.getId());
        result.put("total", total);
        result.put("correct", correct);
        result.put("score", score);
        return result;
    }

    @Override
    public SubmissionDetailsVO getDetails(Long submissionId) {
        var submission = quizSubmissionMapper.findById(submissionId);
        if (submission == null) {
            return null;
        }
        var items = userAnswerMapper.listDetailsBySubmissionId(submissionId);
        SubmissionDetailsVO vo = new SubmissionDetailsVO();
        vo.setSubmissionId(submission.getId());
        vo.setSubject(submission.getSubject());
        vo.setUserId(submission.getUserId());
        vo.setTotal(submission.getTotalQuestions());
        vo.setCorrect(submission.getCorrectCount());
        vo.setScore(submission.getScore());
        vo.setItems(items);
        return vo;
    }
}


